import { listModel } from '@/api/threeModel';
import { find } from '@u/tree';

/********************************************************树形数据**********************************/
export function treeFn(handleNodeClick) {
	// 筛选节点
	const refTree = shallowRef(null),
		filterText = ref('');
	watch(filterText, (val) => {
		refTree.value?.filter(val);
	});
	function filterNode(value, data) {
		if (!value) return true;
		return data.title.includes(value);
	}

	// 数据
	const treeList = ref([]);
	function loadData() {
		listModel().then((res) => {
			treeList.value = res.data;
			const data = find(treeList.value, true, (item) => item.type === 'Y');
			if (data) {
				handleNodeClick(data);
				nextTick(() => {
					refTree.value?.setCurrentKey(data.id);
				});
			}
		});
	}

	return {
		refTree,
		filterText,
		filterNode,
		treeList,
		loadData
	};
}

/*******************************右键菜单************************/
export function rightMenuFn(insertFn, updateFn, removeFn) {
	// 右键菜单处理
	const menuOptionsData = {
			M: [
				{
					label: '新增目录',
					icon: 'FolderAdd',
					fnHandle: () => insertFn(editData.value, '新增目录', 'M')
				},
				{
					label: '新增模型',
					icon: 'CirclePlus',
					fnHandle: () => insertFn(editData.value, '新增模型', 'Y')
				},
				{
					label: '修改',
					icon: 'Edit',
					fnHandle: () => updateFn(editData.value, '目录修改')
				},
				{
					label: '删除',
					icon: 'CircleClose',
					fnHandle: () => removeFn(editData.value)
				}
			],
			Y: [
				{
					label: '修改',
					icon: 'Edit',
					fnHandle: () => updateFn(editData.value, '模型修改')
				},
				{
					label: '删除',
					icon: 'CircleClose',
					fnHandle: () => removeFn(editData.value)
				}
			]
		},
		rightMenuShow = ref(false),
		mousePosition = ref({}),
		menuOptions = ref([]),
		editData = ref([]);

	function handleContextMenu(e, data) {
		e.stopPropagation();
		e.preventDefault();
		// 隐藏旧列表
		rightMenuShow.value = false;
		/***********设置右键按钮功能**************/
		menuOptions.value = menuOptionsData[data.type ?? 'Y'];
		editData.value = clone(data);
		nextTick(() => {
			mousePosition.value = { x: e.clientX, y: e.clientY };
			rightMenuShow.value = true;
		});
	}

	return {
		rightMenuShow,
		mousePosition,
		menuOptions,
		editData,
		handleContextMenu
	};
}
